//
//  GetCaptchaButton.m
//  itboye_jsq_ios
//
//  Created by apple on 15/12/11.
//  Copyright © 2015年 itboye. All rights reserved.
//

#import "GetCaptchaButton.h"

@implementation GetCaptchaButton
{
    NSInteger _countdownTime; // 倒计时剩余时间
    UILabel *_captchaLabel; // 标题
    NSAttributedString *_title; // 可以点击获取验证码时的标题
}

// 自定义初始化方法
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 创建标题label
        _captchaLabel = [[UILabel alloc] initWithFrame:self.bounds];
        [self addSubview:_captchaLabel];
        // 添加文字
        NSDictionary *attrDic = @{NSFontAttributeName:[UIFont systemFontOfSize:14],
                                  NSUnderlineStyleAttributeName:@1,
                                  NSForegroundColorAttributeName:JSQ_COLOR};
        _title = [[NSAttributedString alloc] initWithString:@"获取验证码" attributes:attrDic];
        _captchaLabel.attributedText = _title;
        _captchaLabel.textAlignment = NSTextAlignmentCenter;
    }
    return self;
}


#pragma mark - 获取验证码
// 发送获取验证码请求，并进行下一次按钮允许点击倒计时，防止按钮点击过频
- (void)getCaptchaWithMobile:(NSString *)mobile type:(NSString *)type captchaBlock:(void(^)(NSString *))captchaBlock
{
    // 禁止点击
    self.enabled = NO;
    
    // 再次获取验证码定时器倒计时60秒
    _countdownTime = 30;
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(_countdownAction:) userInfo:nil repeats:YES];
    [timer fire];
    
    NSDictionary *dic = @{@"mobile":mobile, @"code_type":type};
    // 请求验证码
    [BoyeHttpClient post:JSQ_GET_CAPTCHA apiVerson:100 params:dic success:^(AFHTTPRequestOperation *operation, id result) {
        
        NSString *captcha = [[NSString alloc] initWithFormat:@"%@",result];
        
        if (![captcha isStringNull]) {
            [SVProgressHUD showOnlyStatus:captcha withDuration:1];
            if (captchaBlock) {
                captchaBlock(captcha);
            }
        }
        
    } failure:nil];
}


#pragma mark - 倒计时处理
- (void)_countdownAction:(NSTimer *)timer
{
    if (_countdownTime > 0) {
        _countdownTime --;
        _captchaLabel.text = [NSString stringWithFormat:@"(%li)重新获取",_countdownTime];
        _captchaLabel.textColor = [UIColor grayColor];
        _captchaLabel.font = [UIFont systemFontOfSize:13];
    }
    else {
        _captchaLabel.attributedText = _title;
        self.enabled = YES;
        [timer invalidate];
    }
}


@end
